from PySide6.QtWidgets import QProgressDialog, QApplication
from PySide6.QtCore import Qt, QTimer

class ProgressWidget:
    """任务进度弹窗（适合异步任务使用）"""
    def __init__(self, parent=None, text="处理中..."):
        self.dialog = QProgressDialog(text, None, 0, 0, parent)
        self.dialog.setWindowTitle("请稍候")
        self.dialog.setWindowModality(Qt.ApplicationModal)
        self.dialog.setCancelButton(None)
        self.dialog.setMinimumDuration(200)   # 小于200ms的任务不弹窗（防闪）
        self.dialog.setAutoClose(False)       # 防止线程结束自动关闭
        self.dialog.setAutoReset(False)

    def show(self, text=None):
        """显示等待弹窗"""
        if text:
            self.dialog.setLabelText(text)
        self.dialog.setValue(0)
        self.dialog.show()
        QApplication.processEvents()  # 保证立即绘制出来

    def update_text(self, text):
        """动态更新显示文字"""
        self.dialog.setLabelText(text)
        QApplication.processEvents()

    def close(self):
        """安全关闭"""
        QTimer.singleShot(100, self.dialog.close)
